// pages/product/confirm/confirm.js
const app = getApp(),
    globalData = app.globalData,
    utils = require('../../../utils/util'),
    api = require('../../../api/index'),
    pay = require('../../../utils/pay');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isIpx: globalData.isIpx,
        checked: false,
        showCoupon: false,
        couponList: [],
        couponCut: 0, // 优惠券减免
        addressList: [],
        docId: '', // 皮肤管理师编号
        remark: '', // 买家留言
        filter: {
            userAddressId: "",
            userCouponId: "",
            remarks: "",
            orderDetails: [
                {
                    goodsId: "",
                    num: 0,
                    goodsSSpecId: "",
                    // orderDoctorRequests: [
                    //     {
                    //         doctorId: ""
                    //     }
                    // ]
                }
            ],
            orderType: 0, // 1 人气 2 黑标 3 门槛
            appointmentTime: "",
            deliveryTime: "",
            invitationId: '',
            doctorUserId: ''
        },
        filter2: {
            userAddressId: "",
            userCouponId: "",
            remarks: "",
            goodsSeckillId: "",
            goodsSSpecId: "",
            num: 0,
            orderType: 0,
            appointmentTime: "",
            deliveryTime: "",
            invitationId: "",
            doctorUserId: ""
        },
        filter3: {
            orderSpellId: "", // 拼团id，有就是加入拼团，没有就是发起拼团
            goodsId: "",
            goodsSSpecId: "",
            userAddressId: "",
            userCouponId: "",
            remarks: "",
            num: 1,
            orderType: 0,
            appointmentTime: "",
            deliveryTime: "",
            invitationId: "",
            doctorUserId: ""
        },
        toast: {
            visible: false,
            text: ''
        },
        status: 0,
        imageBaseUri: globalData.imageBaseUri,
        discount: 0,
        discountList: [],
        agentInfo: {}, // 顾问信息
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options, 'options')
        let orderInfo = JSON.parse(decodeURIComponent(options.goods));
        console.log(orderInfo, 'orderInfo111')
        if (options.from == 0) {
            for (let i = 0; i < orderInfo.length; i++) {
                for (let j = 0; j < orderInfo[i].GoodsPageDto.GoodsSpecDtos.length; j++) {
                    if (orderInfo[i].GoodsSpecId == orderInfo[i].GoodsPageDto.GoodsSpecDtos[j].Id) {
                        orderInfo[i].GoodsSpecName = orderInfo[i].GoodsPageDto.GoodsSpecDtos[j].Name;
                        orderInfo[i].GoodsPageDto.Price = orderInfo[i].GoodsPageDto.GoodsSpecDtos[j].Price;
                    }
                }
            }
        }


        this.setData({
            orderInfo,
            from: options.from || 0, // 1 来自详情页面 0 来自购物车 2 补货 3 自提
            isGroup: options.group == 'true' ? true : false,
            groupId: options.groupId || '', // 加入拼团就有，创建拼团就没有
        })
        console.log(this.data.orderInfo, 'orderinfo')


        this.reload();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.reload()
    },

    toAddress() {
        wx.navigateTo({
            url: '/pages/product/address/address',
        })
    },

    checkSkin() {
        this.setData({
            checked: !this.data.checked
        })
    },

    reload() {
        if (!utils.getLoginState()) {
            return utils.checkLoginState({
                routeUri: 3,
                uri: `/pages/product/confirm/confirm?goods=${encodeURIComponent(this.data.orderInfo)}&from=${this.data.from}`
            });
        }
        this.getAddress();
        this.getMyCoupons();
        this.getDiscount();
        this.setData({
            agentInfo: wx.getStorageSync('agentInfo') || {}
        })

        // if(this.data.orderInfo){
        // this.getSum();
        // }
    },

    // 获取地址
    async getAddress() {
        try {
            let res = await api.address.getAddressList(),
                data = res.data.ResData || [];
            this.setData({
                addressList: data || [],
                status: 2
            })
            console.log(res, '地址列表')
        } catch (e) {
            console.log(e, '获取地址失败')
        }
    },

    // 获取当前用户的优惠券列表
    async getMyCoupons() {
        try {
            let res = await api.coupon.getMyCoupons(1),
                data = res.data.ResData || [];
            this.setData({
                couponList: data
            })

            // console.log(data[0].CouponDto.Meet, '满足', this.data.sum, 'sum')

            if (data[0] && this.data.sum >= data[0].CouponDto.Meet) {
                // 自动选择第一张优惠券
                this.chooseCoupon();

            }

            console.log(res, '我的优惠券列表')
        } catch (e) {
            console.log(e, '获取我的优惠券列表失败')
        }
    },

    // 显示coupon弹框
    showCoupon() {
        this.setData({
            showCoupon: true
        })
    },

    // 隐藏coupon弹框
    hideCoupon() {
        this.setData({
            showCoupon: false
        })
    },

    // 选择优惠券
    chooseCoupon(e) {
        if (e) {
            let item = e.detail.item;
            console.log(e.detail, 'detail data', item)
            if (this.data.sum < item.CouponDto.Meet) {
                this.setData({
                    toast: {
                        visible: true,
                        text: '未满足使用条件'
                    }
                })
                return
            }
            this.setData({
                couponCut: item.CouponDto.Value,
                chosenCoupon: item
            })
            this.hideCoupon();

        } else {
            if (this.data.couponList && this.data.sum < this.data.couponList[0].CouponDto.Meet) {
                this.setData({
                    toast: {
                        visible: true,
                        text: '未满足使用条件'
                    }
                })
                return
            }
            this.setData({
                couponCut: this.data.couponList && this.data.couponList.length ? this.data.couponList[0].CouponDto.Value : 0,
                chosenCoupon: this.data.couponList && this.data.couponList.length ? this.data.couponList[0] : {}
            })
        }

    },

    // 买家留言
    inputMsg(e) {
        this.setData({
            remark: e.detail.value
        })
    },

    // 皮肤管理师编号
    inputNumber(e) {
        this.setData({
            docId: e.detail.value
        })
    },

    // 提交订单
    async submit(e) {
        console.log(this.data.addressList, 'addreslist')
        if (!this.data.addressList.length) {
            this.setData({
                toast: {
                    visible: true,
                    text: '请选择收货地址'
                }

            })
            return
        }

        console.log(this.data.orderInfo, 'orderInfo');
        let orderInfo = this.data.orderInfo,
            obj = {},
            arr = [];

        // 黑标产品必须填写皮肤管理师编号
        if (orderInfo.length == 1 && (orderInfo[0] && orderInfo[0].type == 2 || orderInfo[0].GoodsPageDto && orderInfo[0].GoodsPageDto.Type == 2)) {
            if (!this.data.docId) {
                this.setData({
                    toast: {
                        visible: true,
                        text: '请填写皮肤管理师编号'
                    }
                })
                return
            }
        }


        orderInfo.forEach(item => {
            if (this.data.from == 1 || this.data.from == 2 || this.data.from == 3) { // 1 来自详情页 2 补货 3 自提
                if (this.data.isGroup) {
                    this.setData({
                        filter3: {
                            orderSpellId: this.data.groupId, // 拼团id，有就是加入拼团，没有就是发起拼团
                            goodsId: item.spec.GoodsId,
                            goodsSSpecId: item.spec.Id,
                            userAddressId: this.data.addressList[0].Id || '',
                            userCouponId: this.data.chosenCoupon && this.data.chosenCoupon.Id || '',
                            remarks: this.data.remark || '',
                            num: 1,
                            orderType: item.type,
                            appointmentTime: "",
                            deliveryTime: "",
                            invitationId: wx.getStorageSync('inviteId') || '',
                            doctorUserId: this.data.docId
                        }
                    })
                } else if (item.spec && item.spec.SeckillPric) {
                    this.setData({
                        'filter2.goodsSeckillId': item.spec.seckillId,
                        'filter2.num': item.count,
                        'filter2.goodsSSpecId': item.spec.Id,
                        'filter2.orderType': item.type
                    })
                } else {
                    // 普通商品参数结构不同
                    if (this.data.from == 2) { // 库存补货下单
                        obj = {
                            goodsId: item.Id,
                            num: item.Num ? item.Num : 1,
                            goodsSSpecId: item.GoodsSpecDtos[0].Id
                        }
                        this.setData({
                            'filter.orderType': item.type || item.Type
                        })
                    } else if (this.data.from == 3) { // 库存自提下单
                        obj = {
                            goodsId: item.GoodsId,
                            num: item.Num ? item.Num : 1,
                            goodsSSpecId: item.GoodsSpecId
                        }
                        this.setData({
                            'filter.orderType': item.type || item.Type
                        })
                    } else {
                        obj = {
                            goodsId: item.spec.GoodsId,
                            num: item.count,
                            goodsSSpecId: item.spec.Id
                        }
                        this.setData({
                            'filter.orderType': item.type || item.Type
                        })
                    }

                    arr.push(obj)
                }

                if (orderInfo[0].spec && orderInfo[0].spec.SeckillPric) {
                    this.setData({
                        filter2: {
                            userAddressId: this.data.addressList[0].Id || '',
                            userCouponId: this.data.chosenCoupon && this.data.chosenCoupon.Id || '',
                            remarks: this.data.remark || '',
                            goodsSeckillId: this.data.filter2.goodsSeckillId || '',
                            num: this.data.filter2.num || 1,
                            goodsSSpecId: this.data.filter2.goodsSSpecId || '',
                            orderType: this.data.filter2.orderType || 0,
                            appointmentTime: "",
                            deliveryTime: "",
                            invitationId: wx.getStorageSync('inviteId') || '',
                            doctorUserId: this.data.docId
                        },
                    })
                }

            } else {
                console.log('来自购物车')
                obj = {
                    goodsId: item.GoodsId,
                    num: item.Num ? item.Num : 1,
                    goodsSSpecId: item.GoodsSpecId
                }
                this.setData({
                    'filter.orderType': item.GoodsPageDto.Type
                })

                arr.push(obj)
            }

        })

        this.setData({
            filter: {
                userAddressId: this.data.addressList[0].Id || '',
                userCouponId: this.data.chosenCoupon && this.data.chosenCoupon.Id || '',
                remarks: this.data.remark || '',
                orderDetails: arr,
                orderType: this.data.filter.orderType || 0,
                appointmentTime: "",
                deliveryTime: "",
                invitationId: wx.getStorageSync('inviteId') || '',
                doctorUserId: this.data.docId
            },

            loading: true
        })


        if (this.data.isGroup) {
            // 拼团下单
            try {
                let res = await api.order.newGroupOrder(this.data.filter3),
                    paymentId = res.data.ResData || '';
                console.log(this.data.filter3, 'filter3参数1')
                if (paymentId) {
                    try {
                        let res = await pay.orderPay(paymentId);

                        this.setData({
                            loading: false
                        })
                        console.log(this.data.filter3, 'filter参数3')
                    } catch (e) {
                        console.log(e, '取消订单')
                        if (e.errMsg == 'requestPayment:fail cancel') {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付取消'
                                },
                                loading: false
                            })
                        } else {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付失败'
                                },
                                loading: false
                            })
                        }
                        return
                    }

                    wx.redirectTo({
                        url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter3.goodsId}`, //&sum=${this.data.sum}&couponcut=${this.data.couponCut}
                    })

                } else {
                    this.setData({
                        toast: {
                            visible: true,
                            text: '支付失败，请重试'
                        }
                    })
                    return
                }

                console.log(res, '提交订单', this.data.filter3, 'filter3')
            } catch (e) {
                this.setData({
                    toast: {
                        visible: true,
                        text: e.data.ErrMsg,
                    },
                    loading: false
                })
                console.log(e, '拼团下单失败')
            }
        } else if (orderInfo[0].spec && orderInfo[0].spec.SeckillPric) {
            // 秒杀商品提交订单
            try {
                let res = await api.order.newSeckillOrder(this.data.filter2),
                    paymentId = res.data.ResData || '';
                console.log(this.data.filter2, 'filter2参数1')
                if (paymentId) {
                    try {
                        let res = await pay.orderPay(paymentId);
                        ;
                        this.setData({
                            loading: false
                        })
                        console.log(this.data.filter2, 'filter参数2')
                    } catch (e) {
                        console.log(e, '取消订单')
                        if (e.errMsg == 'requestPayment:fail cancel') {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付取消'
                                },
                                loading: false
                            })
                        } else {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付失败'
                                },
                                loading: false
                            })
                        }
                        return
                    }

                    wx.redirectTo({
                        url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter2.goodsSeckillId}&sum=${this.data.sum}&couponcut=${this.data.couponCut}`,
                    })

                } else {
                    this.setData({
                        toast: {
                            visible: true,
                            text: '支付失败，请重试'
                        }
                    })
                    return
                }

                console.log(res, '提交订单', this.data.filter, 'filter')
            } catch (e) {
                this.setData({
                    loading: false,
                    toast: {
                        visible: true,
                        text: e.data && e.data.ErrMsg
                    },
                })
                console.log(e, '提交订单失败')
            }
        } else {
            // 普通商品提交订单
            try {
                let res = {};
                if (this.data.from == 1 || this.data.from == 0) {
                    res = await api.order.newOrder(this.data.filter);
                } else if (this.data.from == 2) {
                    res = await api.order.replenishment(this.data.filter);
                } else if (this.data.from == 3) {
                    res = await api.order.selfOrder(this.data.filter);
                }
                // let res = await api.order.newOrder(this.data.filter);
                let paymentId = res.data && res.data.ResData || '';
                console.log(this.data.filter, 'filter参数1')
                if (paymentId) {
                    try {
                        if (this.data.from == 3) {
                            // let res = await api.pay.paynotify()
                        } else {
                            let res = await pay.orderPay(paymentId);
                        }
                        this.setData({
                            loading: false
                        })
                        console.log(this.data.filter, 'filter参数2')
                    } catch (e) {
                        console.log(e, '取消订单')
                        if (e.errMsg == 'requestPayment:fail cancel') {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付取消'
                                },
                                loading: false
                            })
                        } else {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付失败'
                                },
                                loading: false
                            })
                        }
                        return
                    }

                    wx.redirectTo({
                        url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter.orderDetails[0].goodsId}&sum=${this.data.sum}&couponcut=${this.data.couponCut}`,
                    })

                } else {
                    this.setData({
                        toast: {
                            visible: true,
                            text: res.data.ErrMsg || '支付失败，请重试'
                        }
                    })
                    return
                }

                console.log(res, '提交订单', this.data.filter, 'filter')
            } catch (e) {
                this.setData({
                    loading: false,
                    toast: {
                        visible: true,
                        text: e.data && e.data.ErrMsg
                    }
                })
                console.log(e, '提交订单失败')
            }
        }


    },

    // 计算总价
    getSum() {
        let sum = 0,
            chooseArr = this.data.orderInfo;
        console.log(chooseArr, 'chooseArr')
        chooseArr.forEach(item => {
            if (this.data.from == 1) {
                if (this.data.isGroup) {
                    sum += item.spec.SpellGroupPric * item.count
                } else {
                    sum += item.spec.SeckillPric ? item.spec.SeckillPric * item.count : item.spec.Price * item.count
                }
            } else {
                if (this.data.from == 0) {
                    sum += (item.GoodsPageDto.GoodsSpecDtos[0].Price) * Number(item.Num ? item.Num : 1)
                } else if (this.data.from == 2) {
                    sum += (item.Price) * Number(item.Num ? item.Num : 1)
                } else if (this.data.from == 3) {
                    console.log(item, 'mmp', item.GoodsDto.Price, item.Num, (item.GoodsDto.Price) * Number(item.Num))
                    sum += (item.GoodsDto.Price) * Number(item.Num ? item.Num : 1)
                }
            }
        })

        let discount = 0;
        let disList = this.data.discountList || [];

        console.log(disList, 'dislits', disList[0].GreenPrice, '11', disList[1].GreenPrice, '22')

        if (disList.length && !this.data.agentInfo.MemberGradeId) {
            if (sum >= disList[0].GreenPrice && sum < disList[1].GreenPrice) {
                discount = sum * (disList[0].GreenDiscount / 100);
            } else if (sum >= disList[1].GreenPrice) {
                discount = sum * (disList[1].GreenDiscount / 100);
            }
        }


        this.setData({
            sum: sum.toFixed(1),
            discount: discount.toFixed(1)
        })
    },

    // 折扣信息
    async getDiscount() {
        try {
            let res = await api.order.getDiscount(),
                data = res.data || [];

            let discountList = data.splice(0, 2);
            console.log(res, '折扣信息')
            this.setData({
                discountList
            })

            this.getSum()

        } catch (e) {
            console.log(e, '折扣失败')
        }
    }
})